package algorithm.leetcode.medium;

/*
 寻找峰值，峰值元素是指其值大于左右相邻值的元素
 nums[-1] = nums[n] = -∞ 和 nums[i] ≠ nums[i+1] 这两点很重要
 数组可能包含多个峰值，在这种情况下，返回任何一个峰值所在位置即可。
 */

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/12/9
 */
public class Question162 {

    public static void main(String[] args) {
        int[] nums = {1, 3, 2, 4};
        Question162 question = new Question162();
        int index = question.findPeakElement(nums);
        System.out.println(index);
    }

    public int findPeakElement(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        int mid;
        while (left < right) {
            mid = (left + right) / 2;
            if (nums[mid] > nums[mid + 1]) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }

        return left;
    }

    public int findPeakElement1(int[] nums) {
      for (int i = 0; i < nums.length - 1; i++) {
          if (nums[i] > nums[i + 1]) {
              return i;
          }
      }
      return nums.length - 1;
    }
}
